package com.echo.servlet.UserServlet;

import com.echo.servlet.BaseServlet;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import com.echo.dao.UserDao;
import com.echo.entity.User;
import com.echo.util.SessionUtils;

@WebServlet({"/logout", "/echo-network/logout"})
public class LogoutServlet extends BaseServlet {
    private UserDao userDao = new UserDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        setRequestEncoding(request);
        
        boolean logoutSuccess = false;
        
        try {
            // 1. 获取当前会话（若存在则返回，不存在则不创建）
            HttpSession session = request.getSession(false);
            if (session != null) {
                // 从会话中获取当前登录用户信息 - 修复：用户对象存储在"loginUser"属性中
                User currentUser = SessionUtils.getCurrentUser(request);
                
                if (currentUser != null && currentUser.getId() != null) {
                    // 2. 从数据库中删除当前用户数据
                    try {
                        userDao.deleteById(currentUser.getId());
                        System.out.println("用户数据已从数据库中删除，用户ID: " + currentUser.getId());
                    } catch (SQLException e) {
                        System.err.println("删除用户数据失败: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
                
                // 3. 销毁会话，清除登录用户信息
                session.invalidate();
                logoutSuccess = true;
            }


        } catch (Exception e) {
            // 记录异常信息
            e.printStackTrace();
            logoutSuccess = false;
        }
        
        // 5. 重定向到登录页，添加注销状态参数
        response.sendRedirect(request.getContextPath() + "/login.html?logout=" + (logoutSuccess ? "success" : "fail"));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}